# -*- coding: utf-8 -*-
import xlsxwriter as xw
import os
import json
import argparse
import sys
import pandas as pd
import numpy as np
import logging

'''
1. Look for result.json
2. search testcase name and step name
3. split step to request and response
4. write to excel
'''

class Testcase():
    def __init__(self,path,path_excel):
        self.path = path
        self.path_excel = path_excel

    def get_result_file(self):
        files = os.listdir(self.path)
        result_files = []
        container_files = []
        for file in files:
            if 'result' in file:
                result_files.append(file)
            if 'container' in file:
                container_files.append(file)
        self.result_files=result_files
        self.container_files=container_files
        logging.info(f'container_files1:{container_files}')
        return self.result_files,self.container_files

    def get_container(self):
        read_frame_ALl_data = pd.DataFrame()
        read_frame_ALl_data = read_frame_ALl_data.drop(index=read_frame_ALl_data.index)
        # print('read_frame_ALl_data1',read_frame_ALl_data)
        json_datas = None
        for ontainer_file in self.container_files:
            json_path = os.path.join(self.path,ontainer_file)
            with open(json_path,'r',encoding='utf8') as f:
                    all_befores_steps = []
                    all_afters_steps = []
                    json_data = json.load(f)
                    # print('json_data',json_data)
                    children=json_data.get('children','')
                    befores_datas=json_data.get('befores','')
                    # print('befores_datas',befores_datas)
                    if befores_datas:
                            for before_data in befores_datas:
                                    steps = before_data.get('steps','')
                                    if steps:
                                            all_befores_steps.append(steps)
                    afters_datas=json_data.get('afters','')
                    if afters_datas:
                            for after_data in afters_datas:
                                    steps = after_data.get('steps','')
                                    if steps:
                                            all_afters_steps.append(steps)
                    start = json_data.get('start','')
                    stop = json_data.get('stop','')
                    if (children or (all_befores_steps or all_afters_steps)):
                            for uuid in children:
                                    json_datas = pd.Series({'children':uuid,
                                                            "befores": all_befores_steps,
                                                            "afters": all_afters_steps,
                                                            "start": start,
                                                            "stop": stop
                                                            })
                                    # print('json_datas1',json_datas)
                                    read_frame_ALl_data = pd.concat([read_frame_ALl_data,json_datas.to_frame().T],ignore_index=True)
                                    # print('read_frame_ALl_data',read_frame_ALl_data)
        self.read_frame_ALl_data=read_frame_ALl_data
        # print('self.read_frame_ALl_data',self.read_frame_ALl_data)
        return self.read_frame_ALl_data

    def get_testcase(self):
        testcases=[]
        for result_file in self.result_files:
            file_path = os.path.join(self.path,result_file)
            with open(file_path,'r',encoding='utf8') as f:
                testcase = {}
                json_data = json.load(f)
                uuid = json_data['uuid']
                fixtures_datas = self.read_frame_ALl_data[self.read_frame_ALl_data['children']==uuid]
                # print('fixtures_datas:1...',fixtures_datas)
                name = json_data['name']
                testcase['Name']=name
                steps = json_data.get('steps','')
                # print('steps.....',steps)
                for fixture_data in fixtures_datas.values:
                    if fixture_data[1]:
                        print('fixture_data[1].....',fixture_data[1])
                        for befor_fixture_data in fixture_data[1]:
                            # print('befor_fixture_data.....',[befor_fixture_dat])
                            steps = befor_fixture_data + steps
                            print('steps.....',steps)
                            #fixture_data[1]..... [[{'name': 'Step1:Request:设置电压为0', 'status': 'passed', 'start': 1679558102188, 'stop': 1679558103189}, {'name': 'Step2:Request:设置电压为12V', 'status': 'passed', 'start': 1679558103189, 'stop': 1679558108190}]]

                            #steps..... [{'name': 'Step1:Request:设置电压为0', 'status': 'passed', 'start': 1679558102188, 'stop': 1679558103189}, {'name': 'Step2:Request:设置电压为12V', 'status': 'passed', 'start': 1679558103189, 'stop': 1679558108190}, {'name': 'Step1:Request:[0x10,0x01], # Response:[0x50,0x01]', 'status': 'passed', 'start': 1679558108292, 'stop': 1679558108313}, {'name': 'Step1:Request:设置车速为4kph', 'status': 'passed', 'start': 1679558108314, 'stop': 1679558108715}, {'name': "Step2:Request:b'11 01', # Response:b'7f 11 22'", 'status': 'passed', 'start': 1679558108716, 'stop': 1679558108742}, {'name': 'Step3:Request:设置车速为0kph', 'status': 'passed', 'start': 1679558108742, 'stop': 1679558108943}, {'name': 'Step4:Request:sleep1s', 'status': 'passed', 'start': 1679558108943, 'stop': 1679558109944}, {'name': 'Step5:Request:0x11,0x01, # Response:0x51,0x01 check Whether to respond positively after restoring conditions', 'status': 'passed', 'start': 1679558109944, 'stop': 1679558111964}, {'name': 'Step6:Request:设置车速是否有效:SpeedVD_signal=0', 'status': 'passed', 'start': 1679558111964, 'stop': 1679558112164}]

                    if fixture_data[2]:
                        for after_fixture_data in fixture_data[2]:
                            steps =steps + after_fixture_data
                request = []
                response = []
                for i,step in enumerate(steps):
                    step_name=step.get('name','No Step')
                    data = step_name.split('#')
                    if len(data)==2:
                        request.append(str(i+1)+'.'+data[0].strip())
                        response.append(str(i+1)+'.'+data[1].strip())
                    else:
                        request.append(str(i+1)+'.'+data[0].strip())
                        response.append(str(i+1)+'.'+'NA')
                testcase['Request']=request
                testcase['Response']=response
            testcases.append(testcase)
        self.testcases=testcases
        return self.testcases

    def read_excel(self):
        df_exist = True
        if os.path.exists(self.path_excel):
            df = pd.read_excel(self.path_excel,header=0)
        else:
            df = pd.DataFrame()
        if df.empty:
            df_exist = False
        return df,df_exist

    def get_data(self,Function_Mode='',Numb='',Maintainers='',type='',level='P0',link='',Precondition='',Focus='',Comment=''):
        excel_datas = []
        df,df_exist=self.read_excel()      
        for testcase in self.testcases:
            excel_data = {"Function_Mode": '', "Numb": "", "Title": '',
                        'Maintainers':'','Type':'','level':'',
                        'link':'','Precondition':'','Description':'',
                        'Expected':'NA','Focus':'','Comment':''}
            if df_exist:
                excel_testcase = df[df['标题']==testcase['Name']]
                excel_testcase=excel_testcase.fillna('')
                if excel_testcase.empty:
                    excel_data['Function_Mode'] = Function_Mode
                    excel_data['Numb'] = Numb
                    excel_data['Maintainers'] = Maintainers
                    excel_data['Type'] = type
                    excel_data['level'] = level
                    excel_data['link'] = link
                    excel_data['Precondition'] = Precondition
                    excel_data['Focus'] = Focus
                    excel_data['Comment'] = Comment  
                else:
                    excel_data['Function_Mode'] = str(excel_testcase.iloc[0].get('模块',''))
                    excel_data['Numb'] = str(excel_testcase.iloc[0].get('编号',''))
                    excel_data['Maintainers'] = str(excel_testcase.iloc[0].get('维护人',''))
                    excel_data['Type'] = str(excel_testcase.iloc[0].get('用例类型',''))
                    excel_data['level'] = str(excel_testcase.iloc[0].get('重要程度',''))
                    if str(excel_testcase.iloc[0].get('关联需求','')) == '0':
                        excel_data['link'] = link
                    else:
                        # excel_data['link'] = str(excel_testcase.iloc[0].get('关联需求',''))     #目前不支持获取需求号-pingcode
                        excel_data['link'] = link
                    excel_data['Precondition'] = str(excel_testcase.iloc[0].get('前置条件',''))
                    excel_data['Focus'] = str(excel_testcase.iloc[0].get('关注人',''))
                    excel_data['Comment'] = str(excel_testcase.iloc[0].get('备注',''))
            else:
                excel_data['Function_Mode'] = Function_Mode
                excel_data['Numb'] = Numb
                excel_data['Maintainers'] = Maintainers
                excel_data['Type'] = type
                excel_data['level'] = level
                excel_data['link'] = link
                excel_data['Precondition'] = Precondition
                excel_data['Focus'] = Focus
                excel_data['Comment'] = Comment   
            excel_data['Title'] = testcase['Name']         
            str_request=''
            str_response=''
            for i,request in enumerate(testcase['Request']):
                if i == 0:
                    str_request = request
                else:
                    str_request = str_request+'\n'+request
            for i,response in enumerate(testcase['Response']):
                if i == 0:
                    str_response = response
                else:
                    str_response = str_response+'\n'+response
            excel_data['Description'] = str_request
            excel_data['Expected'] = str_response
            excel_datas.append(excel_data)
        self.excel_datas = excel_datas
        return self.excel_datas

    def write_excel(self,filepath):
        fileName=os.path.join(filepath,'测试.xlsx')
        data=self.excel_datas
        workbook = xw.Workbook(fileName)  # 创建工作簿
        worksheet1 = workbook.add_worksheet("sheet1")  # 创建子表
        worksheet1.activate()  # 激活表
        title = ['功能模块', '编号', '*标题','维护人', '用例类型', '重要程度','关联需求', '前置条件', '步骤描述','预期结果', '关注人', '备注']  # 设置表头
        worksheet1.write_row('A2', title)  # 从A2单元格开始写入表头
        i = 3  # 从第二行开始写入数据
        for j in range(len(data)):
            insertData = [data[j]["Function_Mode"],data[j]["Numb"],data[j]["Title"],data[j]["Maintainers"],data[j]["Type"],data[j]["level"],data[j]["link"],data[j]["Precondition"],data[j]["Description"],data[j]["Expected"],data[j]["Focus"],data[j]["Comment"]]
            row = 'A' + str(i)
            worksheet1.write_row(row, insertData)
            i += 1
        workbook.close()  # 关闭表

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.description='This is the input if you need '
    # parser.add_argument('--path',help="this is parameter to select report path",type=str, default="./allure-results")
    parser.add_argument("--module", help="this is parameter to select 功能模块", type=str, default="")
    parser.add_argument("--Numb", help="this is parameter to select 编号", type=str, default="")
    parser.add_argument("--Maintainers", help="this is parameter to select 维护人", type=str, default="") 
    parser.add_argument("--Type", help="this is parameter to select testcase 用例类型", type=str, default="功能测试") 
    parser.add_argument("--level", help="this is parameter to select 重要程度", type=str, default="P0") 
    parser.add_argument("--link", help="this is parameter to select 关联需求", type=str, default="") 
    parser.add_argument("--Precondition", help="this is parameter to select 前置条件", type=str, default="") 
    parser.add_argument("--Focus", help="this is parameter to select 关注人", type=str, default="")             
    parser.add_argument("--Comment", help="this is parameter to select 备注", type=str, default="") 
    args = parser.parse_args()
    # path = args.path

    report_path =  r'D:\project\2_BAIC_B41V\code\allure-results'
    excel_path =   r'D:\project\2_BAIC_B41V\code\allure-results\PingCode_0x11test.xlsx'
    if os.path.exists(report_path):
        print('satrt:')
        tc = Testcase(report_path,excel_path)
        r_file,c_file=tc.get_result_file()
        all_container = tc.get_container()
        all_datas = tc.get_testcase()
        all_datas = tc.get_data(Function_Mode=args.module,type=args.Type)
        tc.write_excel(report_path)
        print('Done!')

    else:
        print('Report_path Error!')



